import store from '../store'

const baseUrl = 'https://getloansmoney.com'

/** 封装fetch请求 */
function Request({ baseURL = baseUrl, url, method = 'GET', headers = {}, data }: { baseURL?: string; url: string; method?: string; headers?: object; data?: any }): Promise<any> {
    const { user } = store.getState()
    return new Promise<any>(async (resolve, reject) => {
        // 配置的参数
        let config: any = {
            mode: 'cors',
            method,
            headers: Object.assign({}, { 'Content-Type': 'application/json' }, headers),
            time: true
        }

        if (user.token) {
            config.headers.token = user.token
        }

        // 判断请求类型
        if (method.toUpperCase() === 'POST' || method.toUpperCase() === 'PUT') {
            config.body = JSON.stringify(data)
        } else if (method.toUpperCase() === 'GET') {
            let str = ''
            for (let key in data) {
                str += `&${key}=${data[key]}`
            }
            if (str.length > 0) {
                if (url.includes('?')) {
                    url += str
                } else {
                    url += `?${str.slice(1)}`
                }
            }
        }

        try {
            const response = await fetch(baseURL + url, config)
            response
                .json()
                .then(res => {
                    console.log('res ok: ', JSON.stringify(res, null, 4))
                    resolve(res)
                })
                .catch(err => {
                    console.log('err: ', err)
                    console.log('url: ', baseURL + url)
                    console.log('method: ', method)
                    console.log('data: ', data)
                    reject(err)
                })
        } catch (err) {
            console.log('err catch: ', err)
            console.log('url: ', baseURL + url)
            console.log('method: ', method)
            console.log('data: ', data)
            reject(err)
        }
    })
}

// 导出配置好的对象
export default Request
